<script setup>
import PageContainer from "@/components/PageContainer.vue";
import { ref } from 'vue'
import { userUpdatePasswordService } from "@/api/user.js";
import { useUserStore } from "@/stores/index.js";
import router from "@/router/index.js";

const userStore = useUserStore()
const formRef = ref()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 自定义校验函数
const checkDifferent = (rule, value, callback) => {
  // 校验新密码不能和原密码一致
  if(value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能和原密码一样'))
  } else {
    callback()
  }
}

const checkSameAsNewPwd = (rule, value, callback) => {
  // 确认密码必须和新密码一致
  if(value !== pwdForm.value.new_pwd) {
    callback(new Error('确认密码必须和新密码一致'))
  } else {
    callback()
  }
}

// 表单校验
const rules = ref({
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min:6, max: 15, message: '原密码必须是6-15位非空字符', trigger: 'blur' },
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min:6, max: 15, message: '新密码必须是6-15位非空字符', trigger: 'blur' },
    { validator: checkDifferent, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min:6, max: 15, message: '确认密码必须和新密码一致', trigger: 'blur' },
    { validator: checkSameAsNewPwd, trigger: 'blur' }
  ],
})

const submitForm = async () => {
  await formRef.value.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success('修改密码成功')

  // 修改成功后 退出登录
  // 清除本地存储的token 和 个人信息
  userStore.setToken('')
  userStore.setUser({})

  router.push('/login')
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="修改密码">
    <!--  表单部分  -->
    <el-form ref="formRef" :model="pwdForm" :rules="rules" label-width="100px" style="margin-left: 20%; margin-top: 5%">
      <el-form-item label="原密码" prop="old_pwd" style="width: 60%">
        <el-input v-model="pwdForm.old_pwd" show-password></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="new_pwd" style="width: 60%">
        <el-input v-model="pwdForm.new_pwd" show-password></el-input>
      </el-form-item>

      <el-form-item label="确认密码" prop="re_pwd" style="width: 60%">
        <el-input v-model="pwdForm.re_pwd" show-password></el-input>
      </el-form-item>

      <el-form-item style="margin-left: 15%">
        <el-button @click="submitForm" type="primary">修改密码</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<style scoped>
el-form-item {
  width: 50%
}
</style>
